package com.wj.auth.controller;

import com.wj.auth.bean.WebResponse;
import com.wj.auth.common.util.jwt.IJWTInfo;
import com.wj.auth.common.util.jwt.JWTHelper;
import com.wj.auth.common.util.jwt.JWTInfo;
import com.wj.auth.configuration.KeyConfiguration;
import com.wj.auth.exception.DuplicationValueException;
import com.wj.auth.exception.auth.UserInvalidException;
import com.wj.auth.service.AuthService;
import com.wj.auth.service.RedisService;
import com.wj.auth.service.UserService;
import com.wj.auth.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/login")
@Api(tags = "登录controller")
@RestController
public class LoginController {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserService userService;

    @Autowired
    private AuthService authService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private KeyConfiguration keyConfiguration;

    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);

    @Value("${jwt.expire}")
    private int expire;

    @PostMapping("/test")
    @ApiOperation("test")
    public String test(){
        return "test";
    }


    @PostMapping("/dologin")
    @ApiOperation("登录")
    public String login(@RequestParam("username") String username, @RequestParam("password")String password) throws Exception {
        if (StringUtils.isEmpty(username)){
            log.error("用户名不存在");
            throw new RuntimeException("用户名不存在");
        }
        UserVO userVO = userService.getUserByUsername(username);

        if (userVO.getStatus() == 2){
            log.error("当前账号被禁用");
            throw new UserInvalidException("当前账号被禁用");
        }
        if(!encoder.matches(password,userVO.getPassword())){
            log.error("帐号密码错误");
            throw new UserInvalidException("帐号密码错误");
        }
        // 获取token
        Map<String, String> map = new HashMap<>();
        map.put("userId", userVO.getId().toString());
        map.put("username", username);
        String body = JSONObject.toJSONString(map);
        String returnMsg = JWTHelper.generateToken(new JWTInfo(username, userVO.getId() + "", userVO.getRealName()), keyConfiguration.getUserPriKey(), expire);
        redisService.set(returnMsg, username);
        return returnMsg;
    }

    @RequestMapping(value = "verify", method = RequestMethod.GET)
    @ApiOperation("校验token")
    public WebResponse verify(String token) throws Exception {
        WebResponse response = new WebResponse();
        Object tokenObject = redisService.get(token);
        if (tokenObject == null){
            throw new DuplicationValueException("登录信息有误");
        }
        IJWTInfo userInfo = authService.validate(token);
        response.setCode(200);
        response.setData(userInfo);
        return response;
    }
}